import { Response } from './../http/response';
import { TokenManager } from './tokenManager';
import { AuthenticationExcption } from './authException';
import IContext = require('koa');

/**
 * Token票据验证
 * 
 * @export
 * @returns
 */
export function authentication() {
    return (target: any, name: string, value: PropertyDescriptor) => {
        if (!Array.isArray(target[name])) target[name] = [target[name]]
        target[name].splice(target[name].length - 1, 0, validateToken)
    }

    async function validateToken(ctx: IContext.Context, next: Function) {
        let token = ctx.request.header.token;
        if (!TokenManager.Current.GetTokenByToken(token)) {
            ctx.response.body = Response.AuthenticateException(new AuthenticationExcption("当前无权限访问！"));
            await next();
        }
    }
}